package com.example.webapi.json;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class jsonUtils {
    private static final Logger logger = LogManager.getLogger(jsonUtils.class);
    /**
     * 递归查找文件
     * @param baseDirName  查找的文件夹路径
     * @param targetFileName  需要查找的文件名
     */
//    public static File findFiles(String baseDirName, String targetFileName,List<String> list) {
//
//        File baseDir = new File(baseDirName);		// 创建一个File对象
//        if (!baseDir.exists() || !baseDir.isDirectory()) {	// 判断目录是否存在
//            System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");
//        }
//        String tempName = null;
//        //判断目录是否存在
//        File tempFile;
//        File[] files = baseDir.listFiles(); //listFiles是获取该目录下所有文件和目录的绝对路径
//        for (int i = 0; i < files.length; i++) {
//            tempFile = files[i];
//            if(tempFile.isDirectory()){
//                findFiles(tempFile.getAbsolutePath(), targetFileName,list);
//            }else if(tempFile.isFile()){
//                tempName = tempFile.getName();
//                if(tempName.equals(targetFileName)){
//                    System.out.println(tempFile.getAbsoluteFile().toString());
//                    // 匹配成功，将文件名添加到结果集
//                    list.add(tempFile.getAbsolutePath());
//                    return tempFile.getAbsoluteFile();
//                }
//            }
//        }
//        return null;
//    }

    public static File findFiles(String baseDirName, String targetFileName,Map<String,Object> map,String url,String prjSid) {
        logger.info("进入findFiles");
        File baseDir = new File(baseDirName);
        if (!baseDir.exists() || !baseDir.isDirectory()) {	// 判断目录是否存在
            System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");
        }
        File[] files = baseDir.listFiles(); //listFiles是获取该目录下所有文件和目录的绝对路径
        File tempFile;
        for (int i = 0; i < files.length; i++) {
            tempFile = files[i];
            // 用于过滤隐藏文件夹
            if (tempFile.isDirectory()){
                String jsonPath = tempFile.getAbsolutePath() + File.separator + targetFileName;
//                System.out.println(jsonPath);

                String jsonStr = readJsonFile(jsonPath);
                Map jsonMap = (Map) JSON.parse(jsonStr);
                map.put(tempFile.getName(),jsonMap);
            }
        }
        // 请求token
        Setting setting = new Setting("config/project.setting");
        String loginPath = setting.getStr("loginPath");
        Map<String,Object> userData = new HashMap<>();
        userData.put("username","admin");
        userData.put("password","123456");
        String loginResult = HttpUtil.post(loginPath, userData);
        JSONObject jsonObject = JSONUtil.parseObj(loginResult);
        Object userInfo = jsonObject.get("data");
        JSONObject mapUserInfo= JSONUtil.parseObj(userInfo);
        Map<String,Object> sendMap = new HashMap<>();
        sendMap.put("token",mapUserInfo.get("sid"));
        sendMap.put("processinstid",prjSid);
        String strData = JSONUtil.toJsonStr(map);
        sendMap.put("jsondata",strData);
        String result= HttpUtil.post(url, sendMap);
        logger.info(result);
        logger.info("请求地址："+result);
        return null;
    }


    /**
     * 读取json文件
     * @param  filePath 文件路径
     * @return 返回json字符串
     */
    public static String readJsonFile(String filePath) {
        File jsonFile  = new File(filePath);
        String jsonStr = "";
        logger.info("————开始读取" + jsonFile.getPath() + "文件————");
        try {
            //File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            logger.info("————读取" + jsonFile.getPath() + "文件结束!————");
            return jsonStr;
        } catch (Exception e) {
            logger.info("————读取" + jsonFile.getPath() + "文件出现异常，读取失败!————");
            e.printStackTrace();
            return null;
        }
    }

    public static void fileWriterMethod(String filepath, Map<String,Object> content) throws IOException {
        try (FileWriter fileWriter = new FileWriter(filepath)) {
            fileWriter.append(JSONUtil.toJsonStr(content));
        }
    }
    public static void main(String[] args) {

//   https://www.cnblogs.com/Big-Boss/p/11252095.html
//  https://blog.csdn.net/wei_chong_chong/article/details/52351158?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.no_search_link

    }
}
